var util = require('util');
var EventEmitter = require('events').EventEmitter;
import { config } from '../config';
var rest = require('../common/rest');
var authRest = require('./auth-rest');

function Heartbeat() {
    EventEmitter.call(this);
    this.online = false;
}

util.inherits(Heartbeat, EventEmitter);

var cloud: any = {
    heartbeat: new Heartbeat(),
    timestamp: getTimestamp,
    startHeartbeat: startHeartbeat
};

function getTimestamp() {
    var url = rest.getUrl('/api/stores/' + config.storeId + '/timestamp');
    return authRest.get(url, {}).then(function (result) {
        return result.timestamp;
    });
}

function startHeartbeat() {
    function heartbeatCheck() {
        return authRest.get(
            rest.getUrl('/api/heartbeat.json', { t: new Date().getTime() }), {}).then(function (result) {
                cloud.heartbeat.online = true;
                cloud.heartbeat.emit("online", true);
            }).catch(function (err) {
                cloud.heartbeat.online = false;
                cloud.heartbeat.emit("online", false);
            });
    }

    function scheduleHearbeatCheck() {
        setTimeout(function () {
            heartbeatCheck().finally(function () {
                scheduleHearbeatCheck();
            });
        }, config.heartBeatSchedule);
    }

    return heartbeatCheck().finally(function () {
        cloud.heartbeat.emit("ready", true);
        scheduleHearbeatCheck();
    });
}

module.exports = cloud;